package com.cbtx.module.base.ui

import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity

/**
 * @作者 zktang
 *
 * @创建时间 2019-06-13 15:15
 *
 * @描述 通用fragment app层抽取
 */
abstract class CommonFragment : Fragment()  {

//    open var mContext : Context? = null
//    open var mActivity : FragmentActivity? = null
    protected var mRootView : View? = null
    private var mIsCreateView = true

//    override fun onAttach(context: Context?) {
//        super.onAttach(context)
//        mContext = activity as Context
//        mActivity = activity
//    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        if(mRootView == null){

                var obj = setLayout()
                if (obj is View) {
                    mRootView = setLayout() as View
                } else if (obj is Int) {
                    mRootView = inflater.inflate(setLayout() as Int, container, false)
                }

        }else{
            var parent = mRootView?.parent
            if(parent != null){
                (parent as ViewGroup).removeView(mRootView)
            }
        }
        return mRootView
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        if(mIsCreateView){
            initView(view, savedInstanceState)
            initData()
            mIsCreateView = false
        }
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        mIsPrepared = true
        lazyLoad()
    }

    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)

        lazyLoad()
    }

    // 设置布局
    protected abstract fun setLayout() : Any

    // 初始化view
    protected abstract fun initView(view : View?, savedInstanceState : Bundle?)

    // 初始化数据
    protected open fun initData(){}

    // 懒加载
    protected open fun lazyData(){}

    // ###############多状态布局处理################
    // 是否启动多状态布局
    protected open fun onIsMultiStateLayout() : Boolean{
        return false
    }





    // ################多状态布局################
    var mIsPrepared = false
    var mIsLazyLoad = false
    private fun lazyLoad(){
        if(userVisibleHint && mIsPrepared && !mIsLazyLoad){
            lazyData()
            mIsLazyLoad = true
        }
    }
    // ################多状态布局################
}